<template>
  <div v-functions="['customer_contact_insert']">
    <div v-if="!noBtn">
      <el-button
        v-if="showBtn"
        icon="el-icon-plus"
        size="mini"
        style="margin-left: 10px"
        @click="openDialog({}, 'add')"
        >联系人</el-button
      >
      <span v-else @click="openDialog({}, 'add')"
        ><i class="el-icon-plus"></i>联系人</span
      >
    </div>
    <MoveDialog
      :visible.sync="visible"
      :before-close="closeDialog"
      class="formRef"
      width="500px"
      :close-on-click-modal="false"
      append-to-body
    >
      <span
        slot="title"
        style="color: #303753; font-size: 14px; font-weight: 600"
        >{{ title }}</span
      >
      <el-form
        ref="formRef"
        class="m7-form"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="联系人姓名" prop="contactName">
          <el-input
            placeholder="请填写联系人姓名"
            v-model.trim="formData.contactName"
            clearable
            :maxlength="20"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input
            placeholder="请填写手机号码"
            v-model.trim="formData.phone"
            :maxlength="20"
            clearable
          >
          </el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="contactEmail">
          <el-input
            placeholder="请填写邮箱"
            :maxlength="50"
            clearable
            v-model.trim="formData.contactEmail"
          >
          </el-input>
        </el-form-item>
        <el-form-item
          label="是否默认"
          prop="isDefault"
          style="margin-bottom: 0px"
        >
          <el-radio-group v-model="formData.isDefault">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog" size="mini">取 消</el-button>
        <el-button type="primary" @click="submit" size="mini">确 定</el-button>
      </div>
    </MoveDialog>
  </div>
</template>

<script lang="ts">
/**
 * 添加联系人按钮
 */
import { Component, Vue, Ref, Prop } from 'vue-property-decorator'
import { deepClone, commonAction, checkHideTel } from '@/utils/common'
import MoveDialog from '@/components/globalTool/moveDialog/index.vue'
// 初始化数据
const defaultForm = {
  contactName: '',
  phone: '',
  isDefault: 0,
  contactEmail: ''
}
@Component({
  name: 'Person',
  components: {
    MoveDialog
  }
})
export default class Person extends Vue {
  [x: string]: any
  @Ref() private readonly formRef: any
  @Prop({ default: () => false }) private showBtn
  @Prop() private customerId
  @Prop({ default: () => false }) private noBtn
  private visible = false
  private formData = deepClone(defaultForm)
  private title = '新增联系人'
  private type = 'add'

  private rules = {
    contactName: [{ required: true, trigger: 'blur', message: '请输入联系人姓名' }],
    phone: [{ required: true, trigger: 'blur', message: '请输入手机号' }],
    contactEmail: [
      { pattern: /^([a-zA-Z0-9]+[_|_|.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|_|.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/g, message: '请填写正确格式的邮箱', trigger: 'blur' }
    ],
    isDefault: [{ required: true, trigger: 'change', message: '请选择是否默认' }]
  }

  // TODO 打开对话框，可以在此填入初始数据
  private openDialog (data: any = {}, type = 'add') {
    this.type = type
    this.title = type === 'add' ? '新增联系人' : '编辑联系人'
    this.formData = type === 'add' ? deepClone(defaultForm) : deepClone(data)
    this.visible = true
  }

  // 关闭对话框
  private closeDialog () {
    this.formRef.clearValidate()
    this.formData = deepClone(defaultForm)
    this.visible = false
  }

  private addOrUpdate () {
    let { contactName, contactEmail, isDefault, _id, phone, realPhone } = this.formData
    if (phone === checkHideTel(realPhone)) { // 加密判断
      phone = realPhone
    }
    if (!(/^[0-9]*$/g.test(phone))) {
      return this.$message.error('手机号只能输入数字')
    }
    const sendData = {
      contactName,
      phone,
      contactEmail,
      isDefault,
      customerId: this.customerId,
      contactorId: _id
    }
    const params = { url: this.type === 'add' ? '/server-crm/action/contactor/add' : '/server-crm/action/contactor/update', method: 'POST', data: sendData }
    commonAction(params).then(res => {
      if (res.success) {
        this.$message.success(`${this.type === 'add' ? '创建' : '修改'}成功`)
        this.$emit('updatePerson', res.data)
        this.closeDialog()
      }
    })
  }

  private defaultCon () {
    commonAction({
      url: '/server-crm/action/contactor/checkContactorDefault',
      method: 'POST',
      data: { customerId: this.customerId, contactorId: this.formData._id }
    }).then(res => {
      if (res.success) {
        if (res.data) {
          this.addOrUpdate()
        } else {
          this.$confirm('检测到当前已有默认联系人，是否进行替换为当前联系人为默认?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.addOrUpdate()
          })
        }
      }
    })
  }

  // 提交
  private async submit () {
    this.formRef.validate(valid => {
      if (valid) {
        if (this.formData.isDefault) {
          this.defaultCon()
        } else {
          this.addOrUpdate()
        }
      }
    })
  }
}
</script>
